package com.dmtt.web.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dmtt.util.R;
import com.dmtt.web.entity.*;
import com.dmtt.web.mapper.CarAlertMapper;
import com.dmtt.web.mapper.CarManagerMapper;
import com.dmtt.web.service.CarManagerService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CarManagerServiceImpl implements CarManagerService {
    @Autowired
    private CarManagerMapper carManagerMapper;

    @Autowired
    private CarAlertMapper carAlertMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${xoffset}")
    private String  xoffset;
    @Value("${yoffset}")
    private String yoffset;
    @Value("${xx}")
    private String xx;
    @Value("${yy}")
    private String yy;

    @Override
    public PageInfo<AgvInfo> findAgvInfo(Integer currPage) {
        PageHelper.startPage(currPage,15);
        List<AgvInfo> agvInfos = carManagerMapper.findAgvInfo(currPage);
        PageInfo<AgvInfo> pageInfo = new PageInfo<>(agvInfos);
        return pageInfo;
    }
    @Override
    public List<AgvInfo> findAgvInfo1() {
        List<AgvInfo> agvInfos = carManagerMapper.findAgvInfo1();

        return agvInfos;
    }

    @Override
    public R queryCar() {
       List<Agv> agv =  carManagerMapper.findAgv();

        return R.ok().put("info",agv);
    }

    @Override
    public void deleteStation(StationUpdate stationUpdate) {
        carManagerMapper.deleteStation(stationUpdate);
    }
    @Override
    public R querySlamCar(){
        List<CarVo> resultAgvDataList = null;
        try {
            JSONObject result = JSONObject.parseObject(restTemplate.getForObject("http://10.148.53.19:62200/api/Agv/GetAllCarrier", String.class));
            JSONObject resData = result.getJSONObject("resData");
            resultAgvDataList = JSONArray.parseArray(resData.getString("ResultAgvDataList"), CarVo.class);
        }catch (Exception e) {
            e.printStackTrace();
        }
        List<CarVo> carVoList1 = resultAgvDataList.stream().filter(carVo -> carVo.getOnline().equals("true")).collect(Collectors.toList());
        List<CarVo>  nocarVoList = resultAgvDataList.stream().filter(carVo -> carVo.getOnline().equals("false")).collect(Collectors.toList());
        List<CarVo> notlinecarList = nocarVoList.stream().filter(carVo -> carVo.getStatus()==1).collect(Collectors.toList());
        carVoList1.addAll(notlinecarList);
        List<Agv> agvs = new ArrayList<>();

        try {
            carVoList1.forEach(carVo -> {
                Agv agv = new Agv();
                if (Double.parseDouble(carVo.getMovementX())>0){
                    agv.setPointX(String.valueOf(Double.parseDouble(carVo.getMovementX()) / Double.parseDouble(xoffset)));
                }else {
                    agv.setPointX(String.valueOf(Double.parseDouble(carVo.getMovementX())* (-1) * Double.parseDouble(xx)));
                }
                agv.setPointY(String.valueOf(Double.parseDouble(carVo.getMovementY()) / Double.parseDouble(yoffset)+Double.parseDouble(yy)));
                agv.setId(Long.parseLong(carVo.getAgvID()));
                agv.setName(carVo.getAgvID());
                agv.setStatusCode(carVo.getStatus().toString());
                agvs.add(agv);
            });
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.ok().put("info",agvs);
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public void updateAgcInfo(AgvInfo agvInfo) {
        carManagerMapper.updateAgcGroupId(agvInfo.getGroupName(),agvInfo.getCarIpAddr(),agvInfo.getCarMacAddr(),agvInfo.getAgvName(),agvInfo.getId());
        List<AgvInfo> agvTargetById = carManagerMapper.findAgvTargetById(agvInfo);
        if (agvTargetById.size()>0){
            int i = carManagerMapper.updateAgcInfo(agvInfo.getCoefficient(), agvInfo.getTarget(), agvInfo.getNonTarget(), agvInfo.getWarningTime(), agvInfo.getAgvName(), agvInfo.getWarningDay(),agvInfo.getId());
//            System.out.println(i);
        }else {
            carManagerMapper.saveAgvTarget(agvInfo.getId(),agvInfo.getAgvName(),agvInfo.getTarget(),agvInfo.getNonTarget(),agvInfo.getWarningTime(),agvInfo.getWarningDay());
        }

    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public R saveAgv(AgvInfo agv) {//添加AGC信息
        List<Agv> agvs = carManagerMapper.queryAgv(agv.getId());
        if (agvs.size()!=0){
            return R.error("id已存在,请更换id");
        }
        if (agv==null || StringUtils.isEmpty(agv.getAgvName()))
            return R.error("agvName为空");
        if (agv.getGroupName()==null)
            return R.error("分组id为空");
        if (StringUtils.isEmpty(agv.getCarIpAddr()))
            return R.error("ip为空");

        carManagerMapper.saveAgv(agv);
        carManagerMapper.saveAgvTarget(agv.getId(),agv.getAgvName(),agv.getTarget(),agv.getNonTarget(),agv.getWarningTime(),agv.getWarningDay());
        return R.ok();
    }


    @Override
    @Transactional(rollbackFor=Exception.class)
    public R deleteAgv(Agv agv) {//删除AGC信息
        if (agv.getId()==null){
            return R.error("id为空");
        }
        carManagerMapper.deleteAgv(agv.getId());
        carManagerMapper.deleteAgvTarget(agv.getId());
        return R.ok();
    }

    @Override
    public PageInfo<FaultInfo>  querymovement(Integer currPage) {//查询稼动率信息
        PageHelper.startPage(currPage,15);
        List<FaultInfo> querymovement = carManagerMapper.querymovement(currPage);
        PageInfo<FaultInfo> pageInfo = new PageInfo<>(querymovement);
        return pageInfo;
    }

    @Override
    public void updatemovement(FaultInfo faultInfo) {
        carManagerMapper.updatemovement(faultInfo.getFaultName(),faultInfo.getEfficientStatus());
    }

    @Override
    public PageInfo<StationUpdate> queryStation(Integer currPage) {
        PageHelper.startPage(currPage,15);
        List<StationUpdate> stationUpdates =  carManagerMapper.queryStation(currPage);
        PageInfo<StationUpdate> pageInfo = new PageInfo<>(stationUpdates);
        return pageInfo;
    }

    @Override
    public void updateStation(StationUpdate stationUpdate) {
        carManagerMapper.updateStation(stationUpdate.getOrigin(),stationUpdate.getJobConfig(),stationUpdate.getX(),stationUpdate.getY(),stationUpdate.getPoint());
    }

    @Override
    public List<AgvInfo> findAgvTarget() {
        return carManagerMapper.findAgvTarget();
    }

    @Override
    public List<StationUpdate> findJobConfig() {
        List<StationUpdate> jobConfig = carManagerMapper.findJobConfig();
        return jobConfig;
    }

    @Override
    public R saveStation(StationUpdate stationUpdate) {
        List<StationUpdate> stationUpdates = carManagerMapper.queryStation(15);
        for (StationUpdate a:stationUpdates){
            if (a.getPoint().equals(stationUpdate.getPoint())){
                return R.ok().put("code",1).put("info",stationUpdates);
            }
        }
        stationUpdate.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        carManagerMapper.saveStation(stationUpdate);
        List<StationUpdate> station = carManagerMapper.queryStation(15);
        PageInfo<StationUpdate> pageInfo = new PageInfo<>(station);
        return R.ok().put("info",pageInfo);
    }

    @Override
    public R warnCarUpdate(AgvInfo agvInfo) {
        carManagerMapper.warnCarUpdate(agvInfo.getWarningStart(),agvInfo.getAgvName());
        return null;
    }

    @Override
    public PageInfo<PointMap> queryPointXY(PointMap pointMap) {
        PageHelper.startPage(pointMap.getCurrPage(),15);
        List<PointMap> pointMaps = carManagerMapper.queryPointXY(pointMap);
        PageInfo<PointMap> pageInfo = new PageInfo<>(pointMaps);
        return pageInfo;
    }

    @Override
    public void savePointXY(PointMap pointMap) {
        pointMap.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        carManagerMapper.savePointXY(pointMap);
    }

    @Override
    public void updatePointXY(PointMap point) {
        carManagerMapper.updatePointXY(point);
    }

    @Override
    public void deletePointXY(PointMap point) {
        carManagerMapper.deletePointXY(point);
    }

    @Override
    public R callPoliceUpdate() {
        Calendar calendar1=Calendar.getInstance();
        calendar1.setTime(new Date());
        calendar1.add(Calendar.HOUR_OF_DAY,0);
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = simpleDateFormat.format(calendar1.getTime());
        List<CallPolice> callPoliceList = carAlertMapper.findCallPolice(startTime,1);
        for (CallPolice callPolice : callPoliceList) {
            carAlertMapper.updateAlert(callPolice.getId(),0);
        }
        return null;
    }
}
